package DAO;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import Hibernate.HibernateUtil;
import Negocio.Proveedor;

public class HibernateProveedorDAO {
	private static HibernateProveedorDAO instancia = null;
	private static SessionFactory sf = null;
	
	
	public static HibernateProveedorDAO getInstancia(){
		if(instancia == null){
			instancia = new HibernateProveedorDAO();
			sf = HibernateUtil.getSessionFactory();
		}
		return instancia;
	}
	
	public Proveedor getProveedor(long cuit){
        try {
        	Session session=sf.openSession();
            session.beginTransaction();
            Query q = session.createQuery("select prov from Proveedor prov left join fetch prov.facturas where prov.cuit = ?").setLong(0, cuit);
            Proveedor proveedor = (Proveedor) q.uniqueResult();
            session.getTransaction().commit();
            session.close();
            return proveedor;
        } catch (Exception e){
            System.out.println(e);
            System.out.println("Error al cargar el Proveedor");
        }
        return null;
	}

	public void grabarProveedor(Proveedor proveedor){
		try{
		Session session = sf.openSession();
		session.beginTransaction();
		session.saveOrUpdate(proveedor);
		session.flush();
		session.getTransaction().commit();
		session.close();
		}catch(Exception e){
			System.out.println(e);
			System.out.println("Error al grabar un Proveedor");
		}
	}
	
	public void updateProveedor(Proveedor proveedor){
		try{
		Session session = sf.openSession();
		session.beginTransaction();
		session.saveOrUpdate(proveedor);
		session.flush();
		session.getTransaction().commit();
		session.close();
		}catch(Exception e){
			System.out.println(e);
			System.out.println("Error al actualizar un Proveedor");
		}
	}

}
